// rdcart_dialog.cpp
//
// A widget to select a Rivendell Cart.
//
//   (C) Copyright 2002-2004 Fred Gleason <fredg@paravelsystems.com>
//
//      $Id: rdcart_dialog.cpp,v 1.32 2007/10/04 20:53:28 dmills Exp $
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 2 as
//   published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public
//   License along with this program; if not, write to the Free Software
//   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//

#include <qpushbutton.h>
#include <qlabel.h>
#include <qsqlquery.h>
#include <qdatetime.h>

#include <rdconf.h>

#include <rdcart_dialog.h>
#include <rdcart_search_text.h>
#include <rdtextvalidator.h>
#include <rddb.h>
//
// Icons
//
#include "../icons/play.xpm"
#include "../icons/rml5.xpm"


RDCartDialog::RDCartDialog(int *cartnum,QString *filter,QString *group,
			   RDCart::Type type,QString *svcname,int svc_quan,
			   QWidget *parent,const char *name)
  : QDialog(parent,name,true)
{
  //
  // Fix the Window Size
  //
  setMinimumWidth(sizeHint().width());
  setMaximumWidth(sizeHint().width());
  setMinimumHeight(sizeHint().height());
  setMaximumHeight(sizeHint().height());

  cart_cartnum=cartnum;
  cart_type=type;
  cart_service=svcname;
  cart_service_quan=svc_quan;
  cart_group=group;

  if(filter==NULL) {
    cart_filter=new QString();
    local_filter=true;
  }
  else {
    cart_filter=filter;
    local_filter=false;
  }

  setCaption(tr("Select Cart"));

  // 
  // Create Fonts
  //
  QFont button_font=QFont("Helvetica",12,QFont::Bold);
  button_font.setPixelSize(12);
  QFont label_font=QFont("Helvetica",12,QFont::Bold);
  label_font.setPixelSize(12);

  //
  // Create Icons
  //
  cart_playout_map=new QPixmap(play_xpm);
  cart_macro_map=new QPixmap(rml5_xpm);

  //
  // Text Validator
  //
  RDTextValidator *validator=new RDTextValidator(this,"validator",true);

  //
  // Filter Selector
  //
  cart_filter_edit=new QLineEdit(this,"cart_filter_edit");
  cart_filter_edit->setGeometry(100,10,360,20);
  cart_filter_edit->setValidator(validator);
  QLabel *label=new QLabel(cart_filter_edit,tr("Cart Filter:"),
			   this,"cart_filter_label");
  label->setGeometry(10,10,85,20);
  label->setAlignment(AlignRight|AlignVCenter);
  label->setFont(label_font);
  connect(cart_filter_edit,SIGNAL(textChanged(const QString &)),
	  this,SLOT(filterChangedData(const QString &)));

  //
  // Filter Clear Button
  //
  cart_clear_button=new QPushButton(this,"cart_clear_button");
  cart_clear_button->setGeometry(470,5,70,30);
  cart_clear_button->setText(tr("C&lear"));
  cart_clear_button->setFont(label_font);
  connect(cart_clear_button,SIGNAL(clicked()),this,SLOT(filterClearedData()));

  //
  // Group Selector
  //
  cart_group_box=new RDComboBox(this,"cart_group_box");
  cart_group_box->setGeometry(100,35,150,20);
  label=new QLabel(cart_group_box,tr("Group:"),
			   this,"cart_group_label");
  label->setGeometry(10,35,85,20);
  label->setAlignment(AlignRight|AlignVCenter);
  label->setFont(label_font);
  connect(cart_group_box,SIGNAL(activated(const QString &)),
	  this,SLOT(groupActivatedData(const QString &)));

  //
  // Cart List
  //
  cart_cart_list=new RDListView(this,"cart_cart_list");
  cart_cart_list->setSelectionMode(QListView::Single);
  cart_cart_list->setGeometry(10,80,
			      sizeHint().width()-20,sizeHint().height()-150);
  cart_cart_list->setAllColumnsShowFocus(true);
  cart_cart_list->setItemMargin(5);
  connect(cart_cart_list,
	  SIGNAL(doubleClicked(QListViewItem *,const QPoint &,int)),
	  this,
	  SLOT(doubleClickedData(QListViewItem *,const QPoint &,int)));
  label=new QLabel(cart_cart_list,"Carts",this,"cart_cart_label");
  label->setGeometry(15,60,100,20);
  label->setFont(button_font);
  cart_cart_list->addColumn("");
  cart_cart_list->setColumnAlignment(0,Qt::AlignHCenter);
  cart_cart_list->addColumn(tr("NUMBER"));
  cart_cart_list->setColumnAlignment(1,Qt::AlignHCenter);
  cart_cart_list->addColumn(tr("LENGTH"));
  cart_cart_list->setColumnAlignment(2,Qt::AlignRight);
  cart_cart_list->addColumn(tr("TITLE"));
  cart_cart_list->setColumnAlignment(3,Qt::AlignLeft);
  cart_cart_list->addColumn(tr("ARTIST"));
  cart_cart_list->setColumnAlignment(4,Qt::AlignLeft);

  cart_cart_list->addColumn(tr("GROUP"));
  cart_cart_list->setColumnAlignment(5,Qt::AlignLeft);


  cart_cart_list->addColumn(tr("CLIENT"));
  cart_cart_list->setColumnAlignment(6,Qt::AlignLeft);
  cart_cart_list->addColumn(tr("AGENCY"));
  cart_cart_list->setColumnAlignment(7,Qt::AlignLeft);
  cart_cart_list->addColumn(tr("USER DEF"));
  cart_cart_list->setColumnAlignment(8,Qt::AlignLeft);
  cart_cart_list->addColumn(tr("START"));
  cart_cart_list->setColumnAlignment(9,Qt::AlignLeft);
  cart_cart_list->addColumn(tr("END"));
  cart_cart_list->setColumnAlignment(10,Qt::AlignLeft);

  //
  // OK Button
  //
  QPushButton *button=new QPushButton(tr("&OK"),this,"ok_button");
  button->setGeometry(sizeHint().width()-180,sizeHint().height()-60,80,50);
  button->setFont(button_font);
  button->setDefault(true);
  connect(button,SIGNAL(clicked()),this,SLOT(okData()));

  //
  // Cancel Button
  //
  button=new QPushButton(tr("&Cancel"),this,"cancel_button");
  button->setGeometry(sizeHint().width()-90,sizeHint().height()-60,80,50);
  button->setFont(button_font);
  connect(button,SIGNAL(clicked()),this,SLOT(cancelData()));

  //
  // Populate Data
  //
  BuildGroupList();
  cart_filter_edit->setText(*cart_filter);
  RefreshCarts();
  RDListViewItem *item=(RDListViewItem *)cart_cart_list->firstChild();
  while(item!=NULL) {
    if(item->text(1).toInt()==*cartnum) {
      cart_cart_list->setSelected(item,true);
      cart_cart_list->ensureItemVisible(item);
      return;
    }
    item=(RDListViewItem *)item->nextSibling();
  }
}


RDCartDialog::~RDCartDialog()
{
  if(local_filter) {
    delete cart_filter;
  }
  delete cart_playout_map;
  delete cart_macro_map;
}


QSize RDCartDialog::sizeHint() const
{
  return QSize(550,370);
}


QSizePolicy RDCartDialog::sizePolicy() const
{
  return QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
}


void RDCartDialog::filterChangedData(const QString &str)
{
  if(str.isEmpty()) {
    cart_clear_button->setDisabled(true);
  }
  else {
    cart_clear_button->setEnabled(true);
  }
  RefreshCarts();
}


void RDCartDialog::filterClearedData()
{
  cart_filter_edit->clear();
  filterChangedData("");
}


void RDCartDialog::groupActivatedData(const QString &group)
{
  RefreshCarts();
  if(cart_group!=NULL) {
    *cart_group=group;
  }
}


void RDCartDialog::doubleClickedData(QListViewItem *,const QPoint &,int)
{
  okData();
}


void RDCartDialog::okData()
{
  RDListViewItem *item=(RDListViewItem *)cart_cart_list->currentItem();
  if(item==NULL) {
    return;
  }

  if(!local_filter) {
    *cart_filter=cart_filter_edit->text();
  }
  *cart_cartnum=item->text(1).toInt();
  done(0);
}


void RDCartDialog::cancelData()
{
  done(-1);
}


void RDCartDialog::closeEvent(QCloseEvent *e)
{
  cancelData();
}


void RDCartDialog::RefreshCarts()
{
  QString sql;
  RDSqlQuery *q;
  RDListViewItem *l;
  RDListViewItem *active_item=NULL;

  cart_cart_list->clear();
  QString group=cart_group_box->currentText();
  if(group==QString("ALL")) {
    group="";
  }
  if(cart_type==RDCart::All) {
    sql=QString().sprintf("select CART.NUMBER,CART.TITLE,CART.ARTIST,\
                           CART.CLIENT,CART.AGENCY,CART.USER_DEFINED,\
                           CART.START_DATETIME,CART.END_DATETIME,CART.TYPE,\
                           CART.FORCED_LENGTH,CART.GROUP_NAME,GROUPS.COLOR \
                           from CART left join GROUPS \
                           on CART.GROUP_NAME=GROUPS.NAME where %s",
		 (const char *)GetSearchFilter(cart_filter_edit->text(),
						group));
  }
  else {
    sql=QString().sprintf("select CART.NUMBER,CART.TITLE,CART.ARTIST,\
                           CART.CLIENT,CART.AGENCY,CART.USER_DEFINED,\
                           CART.START_DATETIME,CART.END_DATETIME,CART.TYPE,\
                           CART.FORCED_LENGTH,CART.GROUP_NAME,GROUPS.COLOR \
                           from CART left join GROUPS \
                           on CART.GROUP_NAME=GROUPS.NAME \
                           where (%s)&&(TYPE=%d)",
		(const char *)GetSearchFilter(cart_filter_edit->text(),group),
			  cart_type);
  }
  q=new RDSqlQuery(sql);
  while(q->next()) {
    l=new RDListViewItem(cart_cart_list);
    switch((RDCart::Type)q->value(8).toUInt()) {
	case RDCart::Audio:
	  l->setPixmap(0,*cart_playout_map);
	  break;

	case RDCart::Macro:
	  l->setPixmap(0,*cart_macro_map);
	  break;

	default:
	  break;
    }
    l->setText(1,QString().sprintf("%06d",q->value(0).toUInt())); // Number
    l->setText(2,RDGetTimeLength(q->value(9).toInt(),false,true)); // Length
    l->setText(3,q->value(1).toString());                       // Title
    l->setText(4,q->value(2).toString());                       // Artist
    l->setText(5,q->value(10).toString());                      // Group
    l->setTextColor(5,q->value(11).toString(),QFont::Bold);
    l->setText(6,q->value(3).toString());                       // Client
    l->setText(7,q->value(4).toString());                       // Agency
    l->setText(8,q->value(5).toString());                       // User Defined
    if(!q->value(6).toDate().isNull()) {
      l->setText(9,q->value(6).toDate().toString("MM/dd/yyyy"));  // Start Date
    }
    if(!q->value(8).toDate().isNull()) {
      l->setText(10,q->value(7).toDate().toString("MM/dd/yyyy"));  // End Date
    }
    else {
      l->setText(10,"TFN");
    }
    if(*cart_cartnum==q->value(0).toInt()) {
      active_item=l;
    }
  }
  delete q;
}


void RDCartDialog::BuildGroupList()
{
  QString sql;
  RDSqlQuery *q;
  
  cart_group_box->clear();
  cart_group_box->insertItem(tr("ALL"));
  sql="select GROUP_NAME from AUDIO_PERMS";
  if(cart_service_quan>0) {
    sql+=" where ";
    for(int i=0;i<cart_service_quan;i++) {
      if(!cart_service[i].isEmpty()) {
	sql+=QString().sprintf("(SERVICE_NAME=\"%s\")||",
			       (const char *)cart_service[i]);
      }
    }
    sql=sql.left(sql.length()-2);
  }
  sql+=" order by GROUP_NAME";
  q=new RDSqlQuery(sql);
  while(q->next()) {
    cart_group_box->insertItem(q->value(0).toString(),true);
  }
  delete q;

  //
  // Preselect Group
  //
  if(cart_group!=NULL) {
    for(int i=0;i<cart_group_box->count();i++) {
      if(*cart_group==cart_group_box->text(i)) {
	cart_group_box->setCurrentItem(i);
	return;
      }
    }
  }
}


QString RDCartDialog::GetSearchFilter(QString filter,QString group)
{
  QString sql;
  RDSqlQuery *q;

  QString search=RDCartSearchText(filter,group).utf8();

  //
  // Excluded Groups
  //
  sql=QString().sprintf("select NAME from GROUPS where ");
  for(int i=1;i<cart_group_box->count();i++) {
    sql+=QString().sprintf("(NAME!=\"%s\")&&",
			   (const char *)cart_group_box->text(i));
  }
  sql=sql.left(sql.length()-2);
  q=new RDSqlQuery(sql);
  while(q->next()) {
    search+=QString().sprintf("&&(GROUP_NAME!=\"%s\")",
			      (const char *)q->value(0).toString());
  }
  delete q;
  return search;
}

